import router, { constantRoutes, getDynamicRoutes } from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, getTokenByName } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { routerListFun } from '@/router/Jurisdiction'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  console.log("prrmission==1=="+to.path+" token="+hasToken)
  console.log("prrmission==2=="+to.path+" token="+getTokenByName("admin_access_token"))

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      // const hasRoles = store.getters.user_role && store.getters.user_role.length > 0
        console.log("prrmission=2="+JSON.stringify(hasRoles))
      const hasRoles = store.getters.user_routes

        console.log("prrmission=2="+JSON.stringify(hasRoles))
      if (hasRoles) {
        console.log("prrmission=4=")

        next()
      } else {
        try {
          console.log("prrmission=3=")

          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          // console.log("prrmission=3="+replace)
          const { roles, routes } = await store.dispatch('user/getInfo')

          let hxyUser={
                account:store.getters.name,
                password:store.getters.hxy_pwd,
                tenant_id:store.getters.user_organize,
                // bindcode:store.getters.name
          }

          if(store.getters.user_role=='RA0003'||store.getters.user_role=='RA0005'){
            //这里是华栖云后台登录接口
            await store.dispatch('user/loginHXY',hxyUser)
          }

          // console.log("hxyUse=="+JSON.stringify(hxyUser))
          //这里是华栖云后台登录接口
          // await store.dispatch('user/loginHXY',hxyUser)

         // const hxyUser = {
         //    "account":"testklmb",
         //    "password":"111111",
         //    "tenant_id":"ZIB7EZ",
         //    "bindcode":"testklmb"
         //  }
         //
         //  // this.loginForm.tenant_id = 251
         //  const { } =  await store.dispatch('user/loginHXY',hxyUser)
         //  this.$store.dispatch('', this.loginForm).then(
         //
         //    (reshxy)=>{//成功
         //      console.log("hxy-成功")
         //
         //      this.loading = false
         //    }).catch(()=>{
         //    console.log("hxy-失败")
         //    this.loading = false
         //  })



          // generate accessible routes map based on roles
          // const accessRoutes = await store.dispatch('permission/generateRoutes', roles)

          let accessRoutes = []
          let arr = routes.split(',')
          arr.forEach(function(value, index, arr) {
            arr[index] = parseInt(value)
          })

          let dynamicRoutes = getDynamicRoutes()

          console.log("prrmission=5="+JSON.stringify(arr))
          let arrRouter = routerListFun(arr, dynamicRoutes)

          // console.log("prrmission=6="+JSON.stringify(routes))
          for (let i = 0; i < arrRouter.length; i++) {
            // if(arrRouter[i].component==""){
            //   arrRouter[i].component = mapComponent.get( arrRouter[i].id)
            // }
            accessRoutes.push(arrRouter[i])
            // router.addRoutes(arrRouter[i])
          }
          let aaa = constantRoutes.concat(accessRoutes)
          // console.log("prrmission=7="+JSON.stringify(accessRoutes))

          // dynamically add accessible routes
          router.addRoutes(aaa)
          router.options.routes = aaa
          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true })
          // next()

        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
